<script setup>
/**
 * 作者: 石兴龙
 * 抖音: 程序员小石
 * 微信: Codingxiaoshi
 */

import { watch, ref, onMounted, nextTick, reactive, } from 'vue';
import EventHub from '../../utils/eventHub';
import { systemStore } from '../../store/system';
import { renderCanvas, getLyc } from '../../utils/index';

const system = systemStore();
const audioDom = ref();
const canvasDom = ref();
const audioProcess = ref(0);
const processChunk = ref();
const lyc = reactive({
  arr: [],
  currentStr: ''
}); // 歌词
let isMoveProcessChunk = false

watch(() => system.audioStatus, async () => {
  console.log('watch', system.audioStatus);
  if (system.audioStatus === 'play') {
    audioDom.value.play()
    lyc.arr = await getLyc(system.currentAudio.audioLyc)
  } else if (system.audioStatus === 'stop') {
    audioDom.value.pause()
  }
})

onMounted(() => {
  audioDom.value.addEventListener('timeupdate', () => {
    if (isMoveProcessChunk === false) {
      const { currentTime, duration } = audioDom.value;
      console.log(currentTime, duration, lyc)
      audioProcess.value = Math.floor(currentTime / duration * 100);
      for (let i = 0; i < lyc.arr.length; i++) {
        let index = i
        const item = lyc.arr[index];
        if (item.time > currentTime) {
          index--
          if (index <= 0) {
            index = 0
          }
          lyc.currentStr = lyc.arr[index].label
          break;
        }
      }
    }
  })
  // 一首歌播完了, 切歌
  audioDom.value.addEventListener('ended', () => {
    system.audioNext()
    EventHub.emit('audioRestore')
  })
  // 绘制 节奏灯
  renderCanvas(audioDom.value)

  // 注册进度条事件
  nextTick(() => moveProcess())
})

EventHub.on('audioRestore', async () => {
  lyc.arr = []
  audioDom.value.currentTime = 0
  audioProcess.value = 0
  audioDom.value.pause()
  lyc.arr = await getLyc(system.currentAudio.audioLyc)
  if (system.audioStatus === 'play') {
    setTimeout(() => {
      audioDom.value.play()
    }, 0)
  }
})
// 点击进度条
const changeProcess = (e) => {
  if (e.target.className === 'process') {
    const process = e.offsetX / 330
    audioProcess.value = Math.floor(process * 100);
    // 根据进度算出秒数
    // 总秒数 / 进度
    audioDom.value.currentTime = Math.floor(audioDom.value.duration * process);
  }
}

// 拖拽进度条
const moveProcess = () => {
  let clientX = 0;
  let startX = 140;
  const pointermove = e => {
    isMoveProcessChunk = true;
    clientX = e.clientX;
    processChunk.value.setPointerCapture(e.pointerId);
    let process = Math.floor((clientX - startX) / processChunk.value.parentElement.offsetWidth * 100)
    if (process > 100) {
      process = 100;
    } else if (process < 0) {
      process = 0;
    }
    audioProcess.value = process;
  }
  processChunk.value.addEventListener('pointerdown', (e) => {
    clientX = e.clientX;
    processChunk.value.addEventListener('pointermove', pointermove)
  })
  processChunk.value.addEventListener('pointerup', (e) => {
    processChunk.value.removeEventListener('pointermove', pointermove)
    processChunk.value.releasePointerCapture(e.pointerId);
    isMoveProcessChunk = false
    audioDom.value.currentTime = Math.floor(audioDom.value.duration * audioProcess.value / 100);
  })
}

</script>

<template>
  <audio ref="audioDom" :src="system.currentAudio.audioSrc"></audio>
  <div class="lyric-container">
    <!-- 歌词部分 -->
    <div class="lyric">
      <p>{{ lyc.currentStr }}</p>
    </div>
    <!-- 节奏灯部分 -->
    <div class="light">
      <canvas id="canvas" ref="canvasDom" width="330" height="63"></canvas>
      <div class="process" @click="changeProcess">
        <label :style="{ width: `${audioProcess}%` }" class="process-bg"></label>
        <span ref="processChunk" :style="{ left: `${audioProcess}%` }" class="process-chunk"></span>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.process {
  width: 330px;
  height: 5px;
  position: absolute;
  cursor: pointer;
  bottom: 0;
  right: 0;
  background: #999;

  .process-bg {
    position: absolute;
    height: 5px;
    bottom: 0;
    pointer-events: none;
    left: 0;
    background: green;
    opacity: .5;
  }

  .process-chunk {
    width: 10px;
    cursor: pointer;
    transform: translateY(25%);
    height: 10px;
    position: absolute;
    bottom: 0;
    left: 0;
    background: rgb(15, 245, 15);
  }
}

canvas {
  background: #333;
  position: absolute;
  bottom: 7px;
  // -webkit-app-region: drag;
  border-top-right-radius: 10px;
  right: 0;
}

.lyric-container {
  width: 400px;
  height: 120px;
  position: relative;

  .lyric {
    // -webkit-app-region: drag;
    height: 50px;
    box-sizing: border-box;
    font-size: 14px;
    color: #fff;
    line-height: 50px;
    padding-left: 60px;
    text-align: center;
    position: absolute;
    width: 100%;
    top: 0;

    p {
      color: rgb(13, 240, 13);
    }
  }

  .light {
    // border: 1px solid red;
    height: 70px;
    width: 100%;
    background: #333;
    position: absolute;
    bottom: 0;
    border-top-right-radius: 10px;
    // overflow: hidden;
  }
}
</style>